﻿using System.Data.SQLite;
using System.Linq;
using CompactMapper.Orm.Extensions;
using CompactMapper.Orm.Queries;
using CompactMapper.Orm.UnitOfWork.Commands.Criteria;
using CompactMapper.Orm.UnitOfWork.Commands.Interfaces;
using CompactMapper.Orm.UnitOfWork.Mappings;

namespace CompactMapper.Orm.UnitOfWork.Commands.Implementations
{
    internal sealed class QueryCommand : Command, IQueryCommand
    {
        public QueryCommand(Table table)
            : base(table)
        {
        }

        public SQLiteDataReader Run(SQLiteConnection connection, Query query, TablesTree tablesTreeRoot)
        {
            var cmd = new SQLiteCommand(connection);
            if (query.Criteria.HasItems())
            {
                var criteria = query.Criteria.Select(criterion => CriteriaFactory.From(criterion, Table, tablesTreeRoot));

                var clauses = criteria.Select(c => c.Clause());
                var builder = new SqlBuilder().Query(Table, clauses);
                cmd.CommandText = builder.ToString();

                var parameters = criteria.Select(c => c.SQLiteParameter()).ExpungeNulls().ToArray();
                cmd.Parameters.AddRange(parameters);
            }
            else
            {
                var builder = new SqlBuilder().SelectAll(Table);
                cmd.CommandText = builder.ToString();
            }
            return cmd.ExecuteReader();
        }
    }
}